import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Rx';


@Injectable()
export class WbsocketService {
  ws: WebSocket;
  constructor() { }
  connect(url: string): Observable<any> {
    this.ws = new WebSocket(url);
    return new Observable(
      observer => {
        this.ws.onopen = event => observer.next('success');
        this.ws.onmessage = event => observer.next(event.data);
        this.ws.onerror = event => observer.error(event);
        this.ws.onclose = event => observer.complete();
      }
    )
  }
  send(message: string) {
    this.ws.send(message);
  }
  close() {
    this.ws.close();
  }
}
